﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Oliving.Edge.AuthHelper
{
    public static class EdgeJWT
    {
        public static object GetJwtToken(
            PermissionRequirement _requirement, string loginName, string userID, string roles, List<PermissionItem> Permissions)
        {
            #region MyRegion
            //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, loginName),
                    new Claim(JwtRegisteredClaimNames.Jti, userID.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
                };

            claims.AddRange(roles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

            _requirement.Permissions = Permissions;
            _requirement.EdgePara = "E:" + DateTime.Now.ToShortTimeString();

            //用户标识
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaims(claims);

            var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);

            #endregion

            return token;
        }
    }
}
